<template>
  <div>
    <div class="min-head" v-if="!isUpdatePwd">
      <a class="text-btn"
        @click="changeDialogType('phoneLogin')"><span>返回</span></a>
    </div>
    <div class="head">
      {{!isUpdatePwd?'设置新密码':userInfo.HasSetPwd?'修改密码':'设置密码'}}
    </div>
    <PhoneForm v-model="form"
      ref="form"
      :phoneDisable="isUpdatePwd"
      pwdPlaceholder="密码为8-16位，必须包含数字和字母"
      :layout="['phone', 'code','pwd','pwd2']"
      @handleEnter="submit"/>
    <el-button class="submit-btn"
        :loading="loading"
        type="primary"
        @click="submit">确定</el-button>
  </div>
</template>

<script type="text/javascript">
import PhoneForm from '@/components/phone-form/index.vue'
import { updatePwd } from '@/api/login'
import { getPwdMD5Str, getTypeOf } from '@/utils'
import { mapGetters } from 'vuex'
export default {
  name: 'UpdatePwd',
  props: {
    isUpdatePwd: {
      type: Boolean,
      default: false
    },
    visible: Boolean
  },
  components: {
    PhoneForm
  },
  data () {
    return {
      form: {
        phoneNumber: '',
        code: '',
        codeID: '',
        pwd: '',
        pwd2: ''
      },
      loading: false
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  watch: {
    visible: {
      handler (val) {
        if (val) {
          this.form.phoneNumber = this.userInfo.PhoneNumber
        }
      },
      immediate: true
    }
  },
  created () {
    if (!this.isUpdatePwd) {
      this.$xz('xz_SetTitleMenuRectEx', {
        x: 16,
        y: 14,
        nx: 24,
        ny: 20
      })
    }
  },
  beforeDestroy () {
    if (!this.isUpdatePwd) {
      this.$xz('xz_SetTitleMenuRectEx', {
        x: 0,
        y: 0,
        nx: 0,
        ny: 0
      })
    }
  },
  methods: {
    /**
     * 提交修改密码
     */
    submit () {
      this.$refs.form.validate().then(() => {
        const params = {
          type: 'phone',
          phoneNumber: this.form.phoneNumber,
          oldPWD: '',
          pwd: getPwdMD5Str(this.form.pwd),
          code: this.form.code,
          codeID: this.form.codeID || this.form.phoneNumber
        }
        this.$refs.form.codeError = ''
        this.loading = true
        updatePwd(params, { offset: 169 }).then(res => {
          this.loading = false
          this.remberAccount(params.phoneNumber, params.pwd)
          this.completeSubmit(params.pwd)
        }).catch(err => {
          if (err && err.code === 12001) {
            this.$refs.form.codeError = '验证码错误'
          }
          this.loading = false
        })
      })
    },
    /**
     * 修改成功
     */
    completeSubmit (pwd) {
      if (!this.isUpdatePwd) {
        this.$xz('xz_substat_action', 1730)
        this.changeDialogType('phoneLogin')
        this.$PsMessage({ message: '密码修改成功，请重新登录' })
      } else {
        this.$xz('xz_substat_action', 1739)
        this.$PsMessage({ message: `密码${this.userInfo.HasSetPwd ? '修改' : '设置'}成功`, iconClass: 'success' })
        // 通知页面
        this.$store.dispatch('user/mergeUserInfo', {
          HasSetPwd: true
        })
        this.$emit('completeUpdatePwd')
      }
    },
    /**
     * 替换记住账号里的密码
     * @param {String} phone
     * @param {String|null} pwd
     */
    remberAccount (phone, pwd) {
      let list = localStorage.getItem('phoneAccount')
      try {
        list = JSON.parse(list)
        if (getTypeOf(list) !== 'array') {
          list = []
        }
      } catch (e) {
        list = []
      }
      for (let i = 0; i < list.length; i++) {
        const item = list[i]
        if (item.a === phone) {
          item.p = ''
          break
        }
      }
      localStorage.setItem('phoneAccount', JSON.stringify(list))
    },
    /**
     * 切换弹框页面
     * @param {String} type
     */
    changeDialogType (type) {
      this.$store.dispatch('user/login', {
        type,
        query: {
          loginType: 'pwd'
        }
      })
    },
    resetFields () {
      this.$refs.form && this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
// @import "@/theme/common/var";
.head {
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 400;
  text-align: center;
  color: #fff;
}
.submit-btn {
  width: 100%;
  margin: 28px 0 50px;
}
</style>
